from django.shortcuts import render, redirect
from .. import models
from ..utils.pagination import Pagination
from ..forms import PrettyModelForm, PrettyEditModelForm

def pretty_list(request):
    """靓号列表"""

    # 创建数据
    # for i in range(9):
    #     models.PrettyNum.objects.create(mobile=f"1377777777{i}", price=10, level=1, status=1)
    data_dict = {}
    # q = 是展示全部
    search_data = request.GET.get("q")
    if search_data:
        data_dict["mobile__contains"] = search_data

    # .all() 表示Selecte * from 表  order by level desc;
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
    page_object = Pagination(request, queryset)
    page_queryset = page_object.page_queryset
    page_string = page_object.html()
    context = {
        "search_data": search_data,
        "queryset": page_queryset,  # 分完页的数据
        "page_string": page_string  # 页码
    }


    return render(request, "app_02/pretty_list.html", context)


def pretty_add(request):
    """添加靓号"""
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, "app_02/pretty_add.html", {"form": form})

    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/app_02/pretty/list")

    return render(request, "app_02/pretty_add.html", {"form": form})


def pretty_edit(request, nid):
    """编辑靓号"""
    row_object = models.PrettyNum.objects.filter(id=nid).first()

    if request.method == "GET":
        form = PrettyEditModelForm(instance=row_object)
        return render(request, "app_02/pretty_edit.html", {"form": form, "row_object": row_object})

    form = PrettyEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/app_02/pretty/list/")
    return render(request, "app_02/pretty_edit.html", {"form": form, "row_object": row_object})


def pretty_delete(request, nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/app_02/pretty/list/")